package cn.sinata.wanglin.mine.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Imageinfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

public class MyphotosActivity extends TitleActivity {
    @BindView(R.id.rv_upphoto)
    RecyclerView rv_upphoto;//所有的相册
    BaseRecyclerAdapter allphotoAdapter;
    private ArrayList<Imageinfo> mImageinfos=new ArrayList<>();
    @Override
    protected int setContentId() {
        return R.layout.activity_myphotos;
    }
    private int MAX_NUMBER=9;
    private String userid;
    @Override
    protected void initView() {
        super.initView();
        setTitle("我的相册");
        userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        Bundle mBundle=getIntent().getExtras();
        if(mBundle!=null){
            mImageinfos= (ArrayList<Imageinfo>) mBundle.getSerializable("mImageinfos");
        }
        GridLayoutManager mgr = new GridLayoutManager(mContext, 4);
        rv_upphoto.setLayoutManager(mgr);
        allphotoAdapter= new BaseRecyclerAdapter<Imageinfo>(mImageinfos, R.layout.item_myimage_grid) {
                @Override
                public void onBind(final int position, final Imageinfo data, ViewHolder holder) {
                    ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(data.getImgUrl());
                     holder.bind(R.id.iv_deletemyimg).setVisibility(View.VISIBLE);
                     holder.bind(R.id.iv_deletemyimg).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            deleteImg(data.getImgID(),position);
                        }
                    });
                }
            };
            allphotoAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ArrayList<String> showPhoto=new ArrayList<String>();
                    for(int i=0;i<mImageinfos.size();i++){
                        showPhoto.add(mImageinfos.get(i).getImgUrl());

                    }
                    ActivityUtil.create(MyphotosActivity.this).go(ImagePagerActivity.class)
                            .put(ImagePagerActivity.URLS,showPhoto)
                            .put(ImagePagerActivity.CURRENT_POSITION,position)
                            .start();
                }
            });
        rv_upphoto.setAdapter(allphotoAdapter);

    }

    @OnClick({R.id.tv_upimg})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_upimg:
                //描述:上传靓照
               int max=(MAX_NUMBER-mImageinfos.size());
                if(max==0){
                    showToast("最多上传9张靓照！");
                    return;
                }
                selectImages();
                break;
        }
    }
    private void selectImages(){
        int max=(MAX_NUMBER-mImageinfos.size());
        ActivityUtil.create(mContext).go(MultiImageSelectorActivity.class)
                .put(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, max)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI)
                .startForResult(2);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==2&&data!=null){
                ArrayList<String> resultList = new ArrayList<>();
                resultList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                upImagesToOss(resultList);

            }
        }
    }

    private void upImagesToOss(ArrayList<String> resultList){

        final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
        for (int i=0;i<resultList.size();i++){
            Utils.systemErr("-path-->"+resultList.get(i));
            mOssBeans.add(new OssBean(resultList.get(i)));
        }

        Observable<List<OssBean>> mObservable= new UpLoadImageUtils(mOssBeans).uploadimg();
        mObservable.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog("上传中...");
               }
               })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        dismissDialog();
                    }
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){

                            JSONArray mJSONArray=new JSONArray();
                            for (int i=0;i<ossBeen.size();i++){
                                Utils.systemErr("-getUrlkey-->"+ossBeen.get(i).getUrlkey());
                                try {
                                    JSONObject mJSONObject=new JSONObject();
                                    mJSONObject.put("imgUrl",ossBeen.get(i).getUrlkey());
                                    mJSONObject.put("userID",Integer.parseInt(userid));
                                    mJSONArray.put(mJSONObject);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }


                            Utils.systemErr("-imgUrl-->"+mJSONArray.toString());
                            uploadImg(mJSONArray.toString());
                        }
                    }
                });


    }
   public void uploadImg(String imgUrl){
       HttpManager.uploadImg(userid,imgUrl).subscribe(new ResultDataSubscriber<ArrayList<Imageinfo>>(this) {
           @Override
           public void onSuccess(String msg, ArrayList<Imageinfo> imageinfos) {
               mImageinfos.addAll(imageinfos);
               allphotoAdapter.notifyDataSetChanged();
           }
       });
   }
    public void deleteImg(String imgID, final int postion){
        HttpManager.delImg(imgID).subscribe(new ResultDataSubscriber<JsonObject>(this) {
            @Override
            public void onSuccess(String msg, JsonObject jsonObject) {
                showToast(msg);
                mImageinfos.remove(postion);
                allphotoAdapter.notifyDataSetChanged();
            }
        });
    }

}
